package net.linku.filter;

import lombok.extern.slf4j.Slf4j;
import net.linku.constant.TraceConstants;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * 全局过滤器，在请求进入时生成并设置 traceId。
 */
@Slf4j
public class GlobalTraceFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String traceId = UUID.randomUUID().toString().replace("-","");
        MDC.put(TraceConstants.TRACE_ID, traceId); // 设置 traceId 到 MDC

        log.info("Generated traceId: {}", traceId); // 添加日志记录 traceId
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove(TraceConstants.TRACE_ID); // 清除 traceId
            log.info("Removed traceId: {}", traceId); // 添加日志记录 traceId 移除
        }
    }

    @Override
    public void destroy() {
        // 销毁方法，可以为空实现
    }
}
